package util

import (
	"math/rand"
	"strings"
	"time"
	"unicode/utf8"
)

// Split Split
func Split(str string, sep string) []string {
	if str == "" { // str "", sep "," 时会返回一个长度为1的字字符串数组
		return []string{}
	}

	return strings.Split(str, sep)
}

// Join Join
func Join(items []string, sep string) string {
	return strings.Join(items, sep)
}

// GetRandomString GetRandomString
func GetRandomString(length int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < length; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}

	return string(result)
}

func GetRandomStringLowerCase(length int) string {
	str := "abcdefghijklmnopqrstuvwxyz"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < length; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}

	return string(result)
}

func GetRandomStringNumber(length int) string {
	str := "0123456789"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < length; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}

	return string(result)
}

// 在一个字符串的开始部份填充字符串
// refer: https://www.cnblogs.com/liyuchuan/p/11081105.html
func PadStart(s string, length int, pad ...string) string {
	if utf8.RuneCountInString(s) >= length {
		return s
	}

	p := " "
	if len(pad) > 0 {
		p = pad[0]
	}

	f := ""
	for i := 0; i < length-utf8.RuneCountInString(s); i++ {
		f += p
	}

	return f + s
}

func UpperFirst(s string) string {
	if s == "" {
		return ""
	}

	return strings.ToUpper(s[:1]) + s[1:]
}

func RegExpEscape(str string) string {
	str = strings.ReplaceAll(str, `\`, `\\`) // must be the first
	str = strings.ReplaceAll(str, "[", `\[`)
	str = strings.ReplaceAll(str, "]", `\]`)
	str = strings.ReplaceAll(str, "(", `\(`)
	str = strings.ReplaceAll(str, ")", `\)`)
	str = strings.ReplaceAll(str, `{`, `\{`)
	str = strings.ReplaceAll(str, `}`, `\}`)
	str = strings.ReplaceAll(str, "+", `\+`)
	str = strings.ReplaceAll(str, "$", `\$`)
	str = strings.ReplaceAll(str, "*", `\*`)
	str = strings.ReplaceAll(str, ".", `\.`)
	str = strings.ReplaceAll(str, "?", `\?`)
	str = strings.ReplaceAll(str, `|`, `\|`)
	str = strings.ReplaceAll(str, `^`, `\^`)

	return str
}

func IsJson(str string) bool {
	s := strings.TrimSpace(str)
	if len(s) < 2 {
		return false
	}

	return (string(s[0]) == "{" && string(s[len(s)-1]) == "}") ||
		(string(s[0]) == "[" && string(s[len(s)-1]) == "]")
}
